<template>
	<navigatorComp
		:title="isEdit ? '编辑资料' : '添加亲人'"
		bgcColor="#121512"
		fontColor="#fff"
	></navigatorComp>

	<view class="content">
		<view class="base_info">
			<image
				@click="chooseAvaterData.show = true"
				class="base_info_avater"
				:src="
					familyInfo.headUrl || 'http://112.124.50.179:8888/imgs/home/obituary_avater.png'
				"
			></image>
			<view class="base_info_uploadText" @click="chooseAvaterData.show = true">
				{{ isEdit ? '修改头像' : '上传照片' }}
			</view>

			<u-form
				label-width="100"
				:label-style="{ fontSize: '28rpx', color: '#ffffff' }"
				:model="familyInfo"
				ref="uForm"
			>
				<view class="display_flex twoInpt" style="gap: 50rpx">
					<u-form-item label="姓:" prop="name" labelWidth="50rpx" required>
						<u-input
							v-model.trim="familyInfo.name"
							border="none"
							placeholder="请输入"
							maxlength="2"
						/>
					</u-form-item>
					<u-form-item label="名:" prop="surname" labelWidth="50rpx" required>
						<u-input
							v-model.trim="familyInfo.surname"
							border="none"
							placeholder="请输入"
							maxlength="4"
						/>
					</u-form-item>
				</view>
				<u-form-item label="性别:" prop="gender" required v-if="!isEdit">
					<up-radio-group activeColor="#7cd172" v-model="familyInfo.gender" size="30rpx">
						<up-radio
							label="男"
							:labelSize="14"
							:name="1"
							labelColor="#ECECEC"
							style="margin-right: 48rpx"
						></up-radio>
						<up-radio
							label="女"
							:labelSize="14"
							:name="2"
							labelColor="#ECECEC"
						></up-radio>
					</up-radio-group>
				</u-form-item>
			</u-form>
		</view>
		<view class="more_info">
			<view class="more_info_title" v-if="!isEdit">更多信息(选填)</view>
			<u-form
				label-width="100"
				:label-style="{ fontSize: '28rpx', color: '#ffffff' }"
				:model="familyInfo"
				ref="uForm"
			>
				<u-form-item label="性别:" prop="gender" required v-if="isEdit">
					<up-radio-group activeColor="#7cd172" v-model="familyInfo.gender" size="30rpx">
						<up-radio
							label="男"
							:labelSize="14"
							:name="1"
							labelColor="#ECECEC"
							style="margin-right: 48rpx"
						></up-radio>
						<up-radio
							label="女"
							:labelSize="14"
							:name="2"
							labelColor="#ECECEC"
						></up-radio>
					</up-radio-group>
				</u-form-item>
				<u-form-item label="生日:" prop="birthday">
					<view
						:class="['placeHolder', familyInfo.birthday && 'value']"
						@click="showBirth = true"
					>
						{{ familyInfo.birthday ? familyInfo.birthday : '请选择生日' }}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
					></image>
					<up-datetime-picker
						:show="showBirth"
						v-model="birthday"
						mode="date"
						:formatter="formatter"
						:minDate="new Date('1920/1/1').getTime()"
						:maxDate="new Date().getTime()"
						@cancel="showBirth = false"
						@confirm="confirmBirth($event)"
					></up-datetime-picker>
				</u-form-item>
				<u-form-item label="祖籍地:" prop="ancestralHomeland">
					<pickerAddress @change="changeAddress">
						<view class="display_flex">
							<view :class="['placeHolder', familyInfo.ancestralHomeland && 'value']">
								{{ familyInfo.ancestralHomeland || '请选择' }}
							</view>
							<image
								class="arrow_right"
								src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
								mode=""
							></image>
						</view>
					</pickerAddress>
				</u-form-item>
				<u-form-item label="现居地:" prop="currentResidence">
					<up-textarea
						v-model="familyInfo.currentResidence"
						border="none"
						height="auto"
						placeholder="请输入现居地"
						:autoHeight="true"
						maxlength="30"
					></up-textarea>
				</u-form-item>
				<u-form-item label="个人简介:" prop="summarize" v-if="isEdit">
					<view class="display_flex">
						<view style="width: 150rpx" class="value singleLineOverflowHidden">
							{{ familyInfo.summarize }}
						</view>
						<image
							@click="goEditSummarize"
							class="arrow_right"
							src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
							mode=""
						></image>
					</view>
				</u-form-item>
				<u-form-item label="结婚纪念日:" prop="weddingDay">
					<view
						:class="['placeHolder', familyInfo.weddingDay && 'value']"
						@click="showWeddingDay = true"
					>
						{{ familyInfo.weddingDay ? familyInfo.weddingDay : '请选择结婚纪念日' }}
					</view>
					<image
						class="arrow_right"
						src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
						mode=""
					></image>
					<up-datetime-picker
						:show="showWeddingDay"
						v-model="weddingDay"
						mode="date"
						:minDate="new Date('1920/1/1').getTime()"
						:maxDate="new Date().getTime()"
						:formatter="formatter"
						@cancel="showWeddingDay = false"
						@confirm="confirmWeddingDay($event)"
					></up-datetime-picker>
				</u-form-item>
				<u-form-item label="备注:" prop="remarks" v-if="isEdit">
					<view class="display_flex">
						<view
							@click="openRemarkPopup"
							:class="['placeHolder', familyInfo.remarks && 'value']"
						>
							{{ familyInfo.remarks || '请选择备注' }}
						</view>
						<image
							@click="openRemarkPopup"
							class="arrow_right"
							src="http://112.124.50.179:8888/imgs/home/arrow_right.png"
							mode=""
						></image>
					</view>
				</u-form-item>
				<u-form-item label="是否在世:" prop="whetherSurvival">
					<view class="display_flex" style="justify-content: space-between; width: 100%">
						<view class="value">
							{{ familyInfo.whetherSurvival === 1 ? '是' : '否' }}
						</view>
						<u-switch
							v-model="familyInfo.whetherSurvival"
							active-color="#F3E0BB"
							@change="changeIsLive"
							:active-value="1"
							:inactive-value="2"
						></u-switch>
					</view>
				</u-form-item>
			</u-form>
		</view>

		<footerBtn
			bgcColor="#121512"
			:btnDisable="btnDisable"
			name="完成"
			@clickBtn="handleAchieve"
		></footerBtn>
	</view>

	<!-- 选择头像 -->
	<myPopup
		v-model:show="chooseAvaterData.show"
		title="选择头像"
		bgColor="#1E201F"
		fontColor="#fff"
		:custom-style="{ minHeight: '524rpx' }"
	>
		<view style="padding: 32rpx 64rpx">
			<view class="family_avaterList">
				<image
					v-for="(item, index) in chooseAvaterData.avaterList"
					@click="chooseAvater(item)"
					:src="item"
					mode="widthFix"
					:class="familyInfo.headUrl === item && 'family_avater_active'"
				></image>
				<image
					src="http://112.124.50.179:8888/imgs/home/family_upload.png"
					mode=""
					@click="uploadImg"
				></image>
			</view>
		</view>
	</myPopup>

	<!-- 选择备注弹框 -->
	<myPopup
		v-model:show="remarkPopup.show"
		title="选择备注"
		bgColor="#1E201F"
		fontColor="#fff"
		height="760rpx"
		@closeCallback="closeRemark_callback"
	>
		<view style="padding: 32rpx">
			<view class="remarkList">
				<view
					@click="chooseRemark(item)"
					v-for="(item, index) in remarkPopup.remarkList"
					:class="['remark', remarkPopup.choosedRemark === item ? 'remark_active' : '']"
				>
					{{ item }}
				</view>
			</view>
		</view>
		<footerBtn bgcColor="#1E201F" name="确定" @clickBtn="confirmRemark"></footerBtn>
	</myPopup>

	<!-- 当亲人不在世的时候，弹出弹框 -->
	<myModel v-model:show="showModel" title="" :showCancelBtn="false" :showConfirmBtn="false">
		<view class="family_model">
			<view class="family_model_close">
				<u-icon name="close" color="#666666" size="23" @click="showModel = false"></u-icon>
			</view>
			<view class="family_model_content">
				愿逝者安息。愿生者坚强在这个艰难时刻,请知道我们与你们同在,愿美好的回忆带给你们安慰,请接受我们最深切的哀悼。
			</view>
			<view class="family_model_btnList">
				<view
					class="family_model_btn"
					@click="
						goUrl('/subPages/home/memoryHall/create_memoryHall');
						showModel = false;
					"
				>
					创建纪念馆
				</view>
				<view
					class="family_model_btn family_model_btn2"
					@click="
						goUrl('/subPages/home/obituary/index');
						showModel = false;
					"
				>
					发布讣告
				</view>
			</view>
		</view>
	</myModel>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, watchEffect, getCurrentInstance } from 'vue';
import navigatorComp from '/components/navigator/index.vue';
import pickerAddress from '/components/picker/addressPicker.vue';
import footerBtn from '/components/footerBtn/index.vue';
import myPopup from '/components/popup/index.vue';
import myModel from '/components/model/index.vue';
import { timeFormat } from '@/node_modules/uview-plus';
import HomeApi from '@/API/home/index.js';
import _ from 'lodash';
const homeApi = new HomeApi();

const $chooseImg = getCurrentInstance().appContext.config.globalProperties.$chooseImg;

const btnDisable = ref(true); //按钮是否可点击
const genealogyId = ref(0); //族谱id
const familyInfo = reactive({
	relationKinsfolkId: 0, //关联亲属id
	kinsfolkId: 0, //亲人id
	addType: 0, //添加类型
	headUrl: '',
	gender: 1,
	surname: '',
	name: '',
	birthday: '',
	ancestralHomeland: '',
	currentResidence: '',
	weddingDay: '',
	whetherSurvival: 1,
	remarks: '',
	summarize: ''
});
const tempAddress = ref([]); //地址临时存储位置
const birthday = ref(new Date()); //生日临时存储位置
const weddingDay = ref(new Date()); //纪念日临时存储位置

const showBirth = ref(false);
const showWeddingDay = ref(false);
const showModel = ref(false);

const isEdit = ref(false); //是否是编辑页
const role = ref(''); //亲人的角色

// 选择备注弹框
const remarkPopup = reactive({
	show: false,
	choosedRemark: '',
	remarkList: [
		'慈父',
		'入赘',
		'吾夫',
		'吾妻',
		'先祖父',
		'先祖母',
		'先外祖父',
		'先外祖母',
		'先兄',
		'先姐',
		'先弟',
		'先妹'
	]
});

// 选择头像
const chooseAvaterData = reactive({
	show: false,
	avaterList: []
});

onLoad((options) => {
	genealogyId.value = options.genealogyId; //族谱id
	familyInfo.kinsfolkId = options.kinsfolkId || 0; //亲人id
	familyInfo.relationKinsfolkId = options.relationKinsfolkId || 0; //关联的亲人id
	familyInfo.addType = options.addType || 0; //添加类型
	familyInfo.gender = options.gender ? Number(options.gender) : 1; //添加人员的性别

	if (options.kinsfolkId) {
		isEdit.value = true;
		getKinsfolkInfo();
	} else {
		isEdit.value = false;
	}
});

watchEffect(() => {
	if (familyInfo.gender === 1) {
		//男
		for (let i = 0; i < 4; i++) {
			chooseAvaterData.avaterList[i] = `http://112.124.50.179:8888/imgs/home/boy${i + 1}.png`;
		}
		console.log(chooseAvaterData.avaterList);
	} else {
		//女
		for (let i = 0; i < 4; i++) {
			chooseAvaterData.avaterList[i] = `http://112.124.50.179:8888/imgs/home/girl${
				i + 1
			}.png`;
		}
	}
});

watchEffect(() => {
	if (familyInfo.surname && familyInfo.name) {
		btnDisable.value = false;
	} else {
		btnDisable.value = true;
	}
});

/**
 * 获取亲人基本信息
 */
const getKinsfolkInfo = () => {
	uni.showLoading();
	homeApi
		.getKinsfolkInfo({
			genealogyId: genealogyId.value,
			kinsfolkId: familyInfo.kinsfolkId
		})
		.then((res) => {
			if (res.code === 0) {
				Object.keys(res.data).forEach((item) => {
					familyInfo[item] = res.data[item];
				});
				familyInfo.ancestralHomeland = res.data.ancestralHomeland.replace(/,/g, '');
				tempAddress.value = res.data.ancestralHomeland.split(',');
			}
			uni.hideLoading();
		});
};

/**
 * 切换是否在世
 */
const changeIsLive = () => {
	console.log(familyInfo.whetherSurvival);
	if (familyInfo.whetherSurvival === 2) {
		//不在世弹出弹框
		showModel.value = true;
	}
};

/**
 * 点击选择头像
 */
const chooseAvater = (item) => {
	familyInfo.headUrl = item;
	chooseAvaterData.show = false;
};

/**
 * 点击添加头像
 */
const uploadAvater = () => {
	chooseAvaterData.show = true;
};

const handleAchieve = _.debounce(
	() => {
		achieve();
	},
	2000,
	{ leading: true, trailing: false }
);

/**
 * 点击完成
 */
const achieve = () => {
	uni.showLoading();
	let params = {
		genealogyId: genealogyId.value,
		...familyInfo,
		ancestralHomeland: tempAddress.value.toString(),
		opType: familyInfo.kinsfolkId ? 2 : 1 //操作类型（1:创建/添加，2:修改）
	};
	homeApi.addKinsfolk(params).then((res) => {
		if (res.code === 0) {
			uni.hideLoading();
			uni.showToast({
				title: familyInfo.kinsfolkId ? '编辑成功！' : '添加成功',
				duration: 500
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 500);
		}
	});
};

/**
 * 前往个人简介编辑页
 */
const goEditSummarize = () => {
	uni.navigateTo({
		url: `/subPages/home/clan/edit_briefIntro?summarize=${familyInfo.summarize}`,
		events: {
			// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
			getSummberize: function (data) {
				familyInfo.summarize = data.summarize;
			}
		}
	});
};

/**
 * 上传文件
 */
const uploadImg = () => {
	$chooseImg
		.chooseImg({
			formData: {
				fileType: 'image',
				fileDirType: 'personal'
			},
			countLimit: 1
		})
		.then((res) => {
			chooseAvaterData.avaterList.push(JSON.parse(res[0].img_url.data).fileUrl);
		});
};

const confirmBirth = (e) => {
	familyInfo.birthday = timeFormat(e.value, 'yyyy-mm-dd');
	showBirth.value = false;
};
const confirmWeddingDay = (e) => {
	familyInfo.weddingDay = timeFormat(e.value, 'yyyy-mm-dd');
	showWeddingDay.value = false;
};

const changeAddress = (e) => {
	tempAddress.value = JSON.parse(JSON.stringify(e.data));
	familyInfo.ancestralHomeland = e.data.join('');
};

/**
 * 打开备注弹框
 */
const openRemarkPopup = () => {
	remarkPopup.show = true;
	remarkPopup.choosedRemark = familyInfo.remark;
};

/**
 * 点击备注
 */
const chooseRemark = (item) => {
	remarkPopup.choosedRemark = item;
};

/**
 * 选择备注——点击确定
 */
const confirmRemark = () => {
	familyInfo.remarks = remarkPopup.choosedRemark;
	remarkPopup.show = false;
};

const formatter = (type, value) => {
	if (type === 'year') {
		return `${value}年`;
	}
	if (type === 'month') {
		return `${value}月`;
	}
	if (type === 'day') {
		return `${value}日`;
	}
	return value;
};

const goUrl = (url) => {
	uni.navigateTo({
		url: url
	});
};
</script>

<style lang="scss">
page {
	background-color: #121512;
	/* #ifdef H5 */
	padding-top: 0;
	/* #endif */
	box-sizing: border-box;
}

.content {
	padding: 0;
	background-color: #121512;
}

.twoInpt {
	::v-deep .u-form {
		width: 100%;
		padding-left: 10rpx;
		box-sizing: border-box;
	}

	::v-deep .u-form-item {
		flex: 1;
	}

	::v-deep .input-placeholder {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999 !important;
		line-height: 33rpx;
		text-align: left !important;
	}

	::v-deep .uni-input-input {
		font-weight: 400;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 33rpx;
		text-align: left !important;
	}

	::v-deep .u-form-item__body__right__content__slot {
		justify-content: flex-start !important;
	}

	.base_info_value {
		font-weight: 400;
		font-size: 32rpx;
		color: #ffffff;
		line-height: 38rpx;
		text-align: left;
	}
}

.base_info,
.more_info {
	margin: 24rpx 32rpx 0;
	box-sizing: border-box;
	padding: 40rpx 32rpx 0;
	background: linear-gradient(225deg, #292b2a 0%, #8a918e 100%);
	border-radius: 8rpx 8rpx 8rpx 8rpx;
	display: flex;
	flex-direction: column;

	::v-deep .u-form {
		width: 100%;
		padding-left: 10rpx;
		box-sizing: border-box;
	}

	::v-deep .u-form-item__body {
		align-items: flex-start !important;
	}

	::v-deep .input-placeholder {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999 !important;
		line-height: 33rpx;
		text-align: right;
	}

	::v-deep .uni-input-input {
		font-weight: 400;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 33rpx;
		text-align: right;
	}

	::v-deep .u-form-item__body__right__content__slot {
		display: flex !important;
		justify-content: flex-end !important;
	}

	::v-deep .u-form-item__body {
		padding: 0 !important;
		margin-bottom: 32rpx !important;
	}

	::v-deep .u-radio-group--row {
		justify-content: flex-end !important;
	}

	::v-deep .uni-textarea-textarea {
		text-align: right !important;
		color: #fff;
		font-size: 28rpx;
	}

	::v-deep .u-textarea {
		padding: 0 !important;
		background: none !important;
		min-height: 33rpx !important;
		max-height: 75rpx !important;
		overflow: scroll;
	}

	.arrow_right {
		width: 40rpx;
		height: 40rpx;
	}

	.placeHolder {
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		line-height: 33rpx;
		text-align: right;
	}

	.value {
		color: #ffffff;
	}
}

.base_info {
	align-items: center;

	.base_info_avater {
		width: 176rpx;
		height: 176rpx;
		margin-bottom: 16rpx;
	}

	.base_info_uploadText {
		font-weight: 400;
		font-size: 24rpx;
		color: #ffffff;
		line-height: 28rpx;
		margin-bottom: 32rpx;
	}
}

.more_info {
	.more_info_title {
		font-weight: 400;
		font-size: 32rpx;
		color: #ffffff;
		line-height: 38rpx;
		margin-bottom: 32rpx;
	}
}

.family_avaterList {
	width: 100%;
	display: grid;
	gap: 32rpx;
	grid-template-columns: 1fr 1fr 1fr 1fr;

	image {
		width: 132rpx;
		max-height: 132rpx;
		overflow: hidden;
	}

	.family_avater_active {
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 4rpx solid #e57ba9;
	}
}

.family_model {
	position: relative;
	width: 100%;

	.family_model_close {
		position: absolute;
		right: -16rpx;
		top: 16rpx;
	}

	.family_model_content {
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		line-height: 42rpx;
		text-align: justify;
		margin-top: 60rpx;
	}

	.family_model_btnList {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 40rpx;

		.family_model_btn {
			width: 210rpx;
			height: 80rpx;
			background: #ffffff;
			border-radius: 40rpx 40rpx 40rpx 40rpx;
			border: 2rpx solid #f3e0bb;
			font-weight: 400;
			font-size: 28rpx;
			color: #0e0e0e;
			line-height: 80rpx;
			text-align: center;
		}

		.family_model_btn2 {
			background-color: #f3e0bb;
		}
	}
}

.remarkList {
	display: flex;
	flex-wrap: wrap;
	margin-right: -20rpx;

	.remark {
		padding: 0 24rpx;
		min-width: 160rpx;
		box-sizing: border-box;
		height: 60rpx;
		background: #333333;
		border-radius: 44rpx 44rpx 44rpx 44rpx;
		font-weight: 400;
		font-size: 28rpx;
		color: #ffffff;
		line-height: 60rpx;
		text-align: center;
		margin-right: 16rpx;
		margin-bottom: 24rpx;
	}

	.remark_active {
		background-color: #f3e0bb;
		color: #0e0e0e;
	}
}
</style>
